<?php


namespace app\common\model;


use think\Exception;

class Task extends BaseModel{
    // 完成任务
    public static function complete($taskId,$userId){
        $task = self::where('id',$taskId)->where('status',1)->find();
        if(empty($task)){
            return false;
        }
        if(self::checkCom($task,$userId)){
            return false;
        }
        return TaskComplete::create([
            'task_id'   => $taskId,
            'user_id'   => $userId,
        ]);
    }


    // 验证任务是否完成
    public static function checkCom($task,$userId){
        if($task['types'] == 1){
            $date = date('Y-m-d');
        }else{
            $date = date('Y-m-d', strtotime("this week Monday", time()));
        }
        $status = TaskComplete::where('task_id',$task['id'])->where('user_id',$userId)->where('created_at','>',$date)->value('status');
        return empty($status) ? 0 : $status;
    }

    public static function receive($task,$userId){
        self::startTrans();
        try{
            if($task['types'] == 1){
                $date = date('Y-m-d');
            }else{
                $date = date('Y-m-d', strtotime("this week Monday", time()));
            }
            TaskComplete::where('task_id',$task['id'])->where('user_id',$userId)->where('created_at','>',$date)->update(['status'=>2]);

            if($task['money'] > 0){
                $addMoneyResult = User::setMoney($userId,'money',$task['money'],'1000','任务奖励');
                if(!$addMoneyResult){
                    throw new Exception('添加金币失败');
                }
            }

            self::commit();
            return true;
        }catch(Exception $e){
            self::rollback();
            write_log($e->getMessage(),'领取任务失败');
            return false;
        }
    }
}